import axios from 'axios'
import router from '../router'
// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:8080/api', // api 的 base_url
    timeout: 8000 // 请求超时时间 10秒
})


service.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
service.defaults.headers['Content-type'] = "application/json"


//request拦截器
service.interceptors.request.use(
    config => {
        let token = window.localStorage.getItem('token')

        let isPermit = (config.url.indexOf("api/auth/") >= 0);

        if (!isPermit) {
            config.headers.Authorization = token // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        console.log("request")
        console.log(config)
        return config
    },
    error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        // return response.data
        console.log("response")
        console.log(response)
        const res = response.data
        if (res.code === 'success' || res.code === 'error') {

        } else if (res.code === 400) {
            router.push('/login')
        } else if (res.code === 401) {
            router.push('/login')
        } else if (res.code === 500) {
            router.push('/500')
        } else if (res.code === 502) {
            router.push('/502')
        } else {
        }
        return res
    },
    error => {
        // 出现网络超时
        console.log("error")
        console.log(error)
        // router.push('/500')
    }
)

export default service
